import { defineStore } from 'pinia';

// 模拟的用户列表，实际项目可从后端获取或用数据库存储
const mockUserList = JSON.parse(localStorage.getItem('mockUserList')) || [];

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,           // 当前用户信息
    token: null,          // 认证令牌
    isLoading: false,     // 加载状态
    error: null,          // 错误信息
    // 模拟存储用户列表，实际应存在后端
    userList: mockUserList 
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    username: (state) => state.user?.username || ''
  },

  actions: {
    // 注册方法，简单模拟，实际需调用后端接口
    async register(username, password) {
      this.isLoading = true;
      this.error = null;

      try {
        // 检查用户名是否已存在
        const existingUser = this.userList.find(user => user.username === username);
        if (existingUser) {
          throw new Error('用户名已存在');
        }

        // 模拟创建用户，实际应调用后端接口创建
        const newUser = { id: Date.now(), username, password };
        this.userList.push(newUser);
        // 保存到本地存储，实际项目可去掉，由后端维护
        localStorage.setItem('mockUserList', JSON.stringify(this.userList));

        return true;
      } catch (error) {
        this.error = error.message || '注册失败';
        return false;
      } finally {
        this.isLoading = false;
      }
    },
    // 登录方法
    async login(username, password) {
      this.isLoading = true;
      this.error = null;

      try {
        // 模拟API请求（实际项目需替换为真实API调用）
        // 这里从模拟的用户列表中查找用户
        const user = this.userList.find(user => user.username === username && user.password === password);
        if (!user) {
          throw new Error('用户名或密码错误');
        }

        const mockToken = 'mock_token_' + Date.now();

        // 存储用户信息到Store
        this.user = user;
        this.token = mockToken;

        // 存储到本地存储，实现持久化
        localStorage.setItem('auth_user', JSON.stringify(user));
        localStorage.setItem('auth_token', mockToken);

        return true;
      } catch (error) {
        this.error = error.message || '登录失败';
        return false;
      } finally {
        this.isLoading = false;
      }
    },

    // 登出方法
    logout() {
      this.user = null;
      this.token = null;
      localStorage.removeItem('auth_user');
      localStorage.removeItem('auth_token');
    },

    // 初始化用户状态（页面刷新时调用）
    initAuth() {
      const user = localStorage.getItem('auth_user');
      const token = localStorage.getItem('auth_token');

      if (user && token) {
        this.user = JSON.parse(user);
        this.token = token;
      }
    }
  }
});